<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\order;

use app\adminapi\controller\Base;
use app\common\model\GoodsOrder as OrderModel;
use app\common\model\UserOrder as UserOrderModel;
use app\service\order\OrderService;

class Order extends Base
{
    /**
     * @notes Order list
     * @auth true
     */
    public function list(OrderModel $model)
    {
        $where = $this->request->params([
            ['date_type', ''],
            ['contact', ''],
            ['trade_no', ''],
            ['transaction_id', ''],
            ['channel_id', ''],
            ['paytype', ''],
            ['status', ''],
            ['date_range', ''],
            ['goods_id', ''],
        ]);
        $res   = $model->with(['channel'])->withSearch($where[0], $where[1])->order("id desc")->paginate($this->limit);
        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * @notes One-click clear invalid orders
     */
    public function clear()
    {
        OrderModel::where('status', 2)->delete();
        $this->success();
    }

    /**
     * @notes Order delete
     * @auth true
     */
    public function del()
    {
        $id  = inputs('id/d', 0);
        $res = OrderModel::where(["id" => $id])->delete();
        UserOrderModel::where(["order_id" => $id])->delete();
        return $res ? $this->success() : $this->error();
    }

    /**
     * @notes Batch delete
     * @auth false
     */
    public function delBatch()
    {
        $ids = inputs("ids/a", []);
        if (empty($ids)) {
            $this->error(trans('please_select_data'));
        }
        $res = OrderModel::whereIn("id", $ids)->delete();
        UserOrderModel::whereIn("order_id", $ids)->delete();
        return $res ? $this->success() : $this->error();
    }

    /**
     * @notes Backend manual payment
     * @auth true
     */
    public function notify()
    {
        $id    = inputs("id/d", 0);
        $order = OrderModel::findOrFail($id);
        $order = (new OrderService())->complete($order);
        $this->success('', $order);
    }
}
